package com.app.shop.util.weixinservice;

import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.View;


public class JsonpView implements View {

	  private String jsonString;
	    private String encoding = "utf-8";
	    
	    private static final Log log = LogFactory.getLog(JsonpView.class);

	    public JsonpView(String jsonString) {
	        this.jsonString = jsonString == null ? "{}" : jsonString;
	    }
	    public JsonpView(String jsonp,String jsonpString){
	    	if(StringUtils.isNotBlank(jsonp)){
	    		this.jsonString = jsonp + "("
						+ jsonpString + ")";
			}else{
				  this.jsonString = jsonpString == null ? "{}" : jsonpString;
			}
	    }
	   /* public JsonpView(String jsonString, String encoding) {
	        this.jsonString = jsonString == null ? "{}" : jsonString;
	        this.encoding = encoding;
	    }*/

	    @Override
	    public String getContentType() {
	        return ResponseHelper.MT_JSONP.concat("; charset=").concat(encoding);
	    }

	    @Override
	    public void render(Map map, HttpServletRequest req,
	            HttpServletResponse res) throws Exception {
	    	
	    	//增加调试日志
		    String exposeKey = req.getParameter("logkey");
		    if(StringUtils.isNotEmpty(exposeKey)){
		    	Object o = map.get(exposeKey);
		    	if(o instanceof Collection || o instanceof Map){
		    		log.warn("logkey[" + exposeKey + "]:" + o);
		    	}else{
			    	try {
			    		log.warn("logkey[" + exposeKey + "]:" + ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE));
			        } catch (Exception e) {
			        	log.error("logkey error:", e);
			        }
		    	}
		    }
	    	
	    	
	        String callback = req.getParameter("callback");
	        String message = jsonString;
	        if (callback != null) {
	            message = callback.concat("(").concat(message).concat(")");
	        }
	        ResponseHelper.send(req,res, message, ResponseHelper.MT_JSON, encoding);
	    }


}
